
package com.scs.application.modules.base.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.DictConsts;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.model.PageResult;
import com.scs.application.core.model.RestResult;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.mvc.controller.ImAndExAbleController;
import com.scs.application.core.threadLock.ThreadLock;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.base.dto.CloseCommonDto;
import com.scs.application.modules.base.entity.Hospital;
import com.scs.application.modules.base.entity.SupplierApplicant;
import com.scs.application.modules.base.mapper.SupplierApplicantMapper;
import com.scs.application.modules.base.request.SupplierApplicantQueryRequest;
import com.scs.application.modules.base.service.HospitalService;
import com.scs.application.modules.base.service.SupplierApplicantService;
import com.scs.application.modules.design.service.QueryGenerator;
import com.scs.application.modules.ext.entity.File;
import com.scs.application.modules.ext.service.FileService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * SupplierApplicant controller
 */
@AllArgsConstructor
@RestController
@RequestMapping("/base/supplier_applicants")
public class SupplierApplicantController extends CrudController<SupplierApplicant, String, SupplierApplicantService> implements ImAndExAbleController<SupplierApplicantQueryRequest> {

    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private SupplierApplicantMapper supplierApplicantMapper;
    @Autowired
    private FileService fileService;

    @GetMapping("/page")
    public PageResult page(SupplierApplicantQueryRequest request) {
        IPage page = service.page(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }


    @GetMapping("/list")
    public CommonResult list(SupplierApplicantQueryRequest request) {
        List<SupplierApplicant> list = service.list(request);
        return CommonResult.ok("查询成功", list);
    }

    /**
     * 供应商资格申请
     *
     * @param entity
     * @return
     */
    @PostMapping("/applicant")
    public CommonResult applicant(@RequestBody @Valid SupplierApplicant entity) {
        SupplierApplicant applicant = service.applicant(entity);
        return applicant != null ? CommonResult.ok("保存成功", applicant) : CommonResult.error("保存失败");

    }

    /**
     * TODO 修改URL 为 /{id}/submit，同时前端也需要修改
     * 供方资格申请提交 制单状态 修改为 提交待审核状态
     *
     * @param id
     * @return
     */
    @PostMapping("/submit/{id}")
    public CommonResult submit(@PathVariable("id") String id) {
        service.submit(id);
        return CommonResult.ok("提交申请成功");
    }

    /**
     * TODO 修改URL 为 /{id}/pass，同时前端也需要修改
     * 供方资格申请审核通过 提交待审核状态 修改为 已审核状态
     *
     * @param id
     * @return
     */
    @PostMapping("/pass/{id}")
    public CommonResult pass(@PathVariable("id") String id) {
        service.pass(id, null);
        return CommonResult.ok("审核通过");
    }

    /**
     * TODO 修改URL 为 /{id}/cancel，同时前端也需要修改
     * 供方资格申请审核不通过 提交待审核状态 修改为 取消状态
     *
     * @param id
     * @param auditedRemark
     * @return
     */
    @PostMapping("/cancel")
    public CommonResult cancel(@RequestBody CloseCommonDto closeCommonDto) {
        service.cancel(closeCommonDto.getId(), closeCommonDto.getRemark());
        return CommonResult.ok("拒绝成功");
    }

    /**
     * TODO 修改URL 为 /page_audit，同时前端也需要修改。service方法也需要修改
     * 审核页
     *
     * @param request
     * @return
     */
    @GetMapping("/pageAudit")
    public PageResult pageAudit(SupplierApplicantQueryRequest request) {
        IPage page = service.pageAudit(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }



    /***
     * @date: 2024/6/24
     * @Description:  添加数据过滤条件
     */
    @Override
    public void fillQueryAuth(QueryWrapper queryWrapper,SupplierApplicant entity) {
        if (UserUtils.isAdmin()) {
            return;
        }
        // 只筛选当前供应商的数据
        boolean isSupplier = false;
        try {
            isSupplier = UserUtils.isSupplier();
        }catch (Exception e) {
        }

        if (isSupplier) {
            queryWrapper.eq("supplier_id", UserUtils.getSupplierId());
        } else {
            queryWrapper.eq("hospital_id", UserUtils.getHospitalId());
        }
    }

    /***
     * @param request
     * @Description:  通用分页
     */
    @GetMapping("/pageCommon")
    public PageResult pageCommon(HttpServletRequest request, SupplierApplicant entity) {
        IPage<SupplierApplicant> page = QueryGenerator.parsePage(request);
        QueryWrapper<SupplierApplicant> queryWrapper = QueryGenerator.initQueryWrapper(request);
        fillQueryAuth(queryWrapper,entity);
        IPage pageResult = service.page(page, queryWrapper);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }

    /***
     * @Description:  外部系统调用-服务商申请信息
     */
    @GetMapping("/getListForTpcItsm")
    public RestResult getListForTpcItsm(String hospitalOid) {
        if (StringUtils.isBlank(hospitalOid)) {
            return  RestResult.error("缺少参数组织代码, hospitalOid");
        }
        Hospital hospital = hospitalService.getOne(Wrappers.<Hospital>query().eq("oid",hospitalOid ), false);
        if (hospital == null) {
            return  RestResult.error(StrUtil.format("未找到相关医院，机构代码:{}",hospitalOid));
        }

        SupplierApplicantQueryRequest queryRequest = new SupplierApplicantQueryRequest();
        queryRequest.setHospitalId(hospital.getId());
        queryRequest.setStatus("1");
        queryRequest.setSupplyType(DictConsts.hp_supply_type_service_itsm);
        List<SupplierApplicant> list = supplierApplicantMapper.listAudit(queryRequest);
        if (!list.isEmpty()) {
            List<String> idList = list.stream().map(SupplierApplicant::getId).collect(Collectors.toList());
            Map<String,List<File>> fileMapByRefId = fileService.list(Wrappers.<File>query().in("ref_id",idList))
                    .stream().collect(Collectors.groupingBy(File::getRefId));
            if (!fileMapByRefId.isEmpty()) {
                List<String> applyFileUrlList;
                for(SupplierApplicant supplierApplicant : list) {
                    if (fileMapByRefId.containsKey(supplierApplicant.getId())) {
                        applyFileUrlList = fileMapByRefId.get(supplierApplicant.getId()).stream().map(File::getFilePath).collect(Collectors.toList());
                        supplierApplicant.setApplyFileUrlList(applyFileUrlList);
                    }

                }
            }
        }
        return RestResult.ok(
                "操作成功",
                list
        );
    }

    /***
     * @Description:  外部系统调用-SCP系统-接收-服务商已审核信息
     */
    @PostMapping("/toEndForTpcItsm")
    public RestResult toEndForTpcItsm(@RequestBody SupplierApplicant entity) {
        synchronized (entity.getId().intern()) {
//            SupplierApplicant supplierApplicantDb = service.getById(entity.getId());
//            if (supplierApplicantDb == null) {
//                return  RestResult.error(StrUtil.format("未找到相关申请单，主键:{}",entity.getId()));
//            }
//            supplierApplicantDb.setGmtAudited(entity.getGmtAudited()).setModifier(entity.getModifier());
//            service.updateCascadeById(supplierApplicantDb);
            service.pass(entity.getId(),entity);
        }

        return RestResult.ok();
    }

}
